﻿using System;
using System.Runtime.CompilerServices;

namespace IndexedFilePackageLibrary
{
    internal static class StringHash
    {
        /// <summary>
        /// FNV-1a Hash functions
        /// </summary>
        public static class Fnv1a
        {
            /// <summary>
            /// Calculate 32-bit FNV-1a hash value
            /// </summary>
            public static uint Hash32(ReadOnlySpan<byte> buffer)
            {
                const uint offsetBasis32 = 2166136261;
                const uint prime32 = 16777619;

                uint result = offsetBasis32;
                int len = buffer.Length;
                for (int i = 0; i < len; i++)
                {
                    result = prime32 * (result ^ buffer[i]);
                }
                return result;
            }

            /// <summary>
            /// Calculate 64-bit FNV-1a hash value
            /// </summary>
            public static ulong Hash64(ReadOnlySpan<byte> buffer)
            {
                const ulong offsetBasis64 = 14695981039346656037;
                const ulong prime64 = 1099511628211;

                ulong result = offsetBasis64;
                int len = buffer.Length;
                for (int i = 0; i < len; i++)
                {
                    result = prime64 * (result ^ buffer[i]);
                }
                return result;
            }
        }
        
    }
}
